<template>
  <div class="warehouse-selector">
    <el-dialog
      :title="title"
      v-model="visible"
      width="850px"  
      append-to-body
      @close="handleClose"
      destroy-on-close
    >
      <!-- 搜索条件 -->
      <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="80px">
        <el-form-item label="仓库编号" prop="warehouseCode">
          <el-input
            v-model="queryParams.warehouseCode"
            placeholder="请输入仓库编号"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="仓库名称" prop="warehouseName">
          <el-input
            v-model="queryParams.warehouseName"
            placeholder="请输入仓库名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="仓库类型" prop="warehouseType">
          <el-select v-model="queryParams.warehouseType" placeholder="请选择仓库类型" clearable>
            <el-option
              v-for="dict in warehouse_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
            <el-option
              v-for="dict in wms_warehouse_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格数据 -->
      <el-table 
        v-loading="loading" 
        :data="warehouseList" 
        @row-click="handleRowClick"
        highlight-current-row
        :row-class-name="rowClassName"
        height="350px"
        border
      >
        <el-table-column label="仓库ID" align="center" prop="warehouseId" width="80" />
        <el-table-column label="仓库编号" align="center" prop="warehouseCode" width="120" />
        <el-table-column label="仓库名称" align="center" prop="warehouseName" width="120" />
        <el-table-column label="仓库类型" align="center" prop="warehouseType" width="100">
          <template #default="scope">
            <dict-tag :options="warehouse_type" :value="scope.row.warehouseType"/>
          </template>
        </el-table-column>
        <!-- <el-table-column label="负责人" align="center" prop="managerName" width="100" /> -->
        <el-table-column label="状态" align="center" prop="status" width="80">
          <template #default="scope">
            <dict-tag :options="wms_warehouse_status" :value="scope.row.status"/>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="操作" align="center" width="100">
          <template #default="scope">
            <el-button 
              link 
              type="primary" 
              @click.stop="selectWarehouse(scope.row)"
              :disabled="!isWarehouseSelectable(scope.row)"
            >选择</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
        :pageSizes="[5, 10, 20, 30]"
        :small="true"
      />

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="confirmSelection" :disabled="!canConfirm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { listWarehouse } from "@/api/wms/warehouse";
import { ref, reactive, toRefs, computed, getCurrentInstance, defineProps, defineEmits, watch } from 'vue';

const { proxy } = getCurrentInstance();
const { wms_warehouse_status, warehouse_type } = proxy.useDict('wms_warehouse_status', 'warehouse_type');

// 定义属性和事件
const props = defineProps({
  title: {
    type: String,
    default: '选择仓库'
  },
  visible: {
    type: Boolean,
    default: false
  },
  filters: {
    type: Object,
    default: () => ({})
  }
});

const emit = defineEmits(['update:visible', 'select']);

// 数据部分
const warehouseList = ref([]);
const loading = ref(false);
const visible = ref(false);
const total = ref(0);
const selectedWarehouse = ref(null);
const selectedRowIndex = ref(null);

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    warehouseCode: null,
    warehouseName: null,
    warehouseType: null,
    status: null
  }
});

const { queryParams } = toRefs(data);

// 计算是否可以确认选择
const canConfirm = computed(() => {
  return selectedWarehouse.value !== null;
});

// 监听visible变化
watch(() => props.visible, (val) => {
  if (val) {
    // 当弹窗显示时初始化数据
    getList();
  }
  visible.value = val;
});

// 监听内部visible变化
watch(() => visible.value, (val) => {
  emit('update:visible', val);
});

// 查询仓库列表
function getList() {
  loading.value = true;
  // 合并基本查询参数与传入的过滤条件
  const params = {
    ...queryParams.value,
    ...props.filters
  };
  
  listWarehouse(params).then(response => {
    warehouseList.value = response.rows || [];
    total.value = response.total;
    loading.value = false;
  }).catch(() => {
    loading.value = false;
  });
}

// 判断仓库是否可选
function isWarehouseSelectable(warehouse) {
  // 通常只有正常状态的仓库可选
  return warehouse.status === '0' || warehouse.status === 0;
}

// 行样式
function rowClassName({row, rowIndex}) {
  let classNames = '';
  
  // 选中行高亮
  if (selectedRowIndex.value === rowIndex) {
    classNames += 'row-selected ';
  }
  
  // 不可选择的仓库行样式
  if (!isWarehouseSelectable(row)) {
    classNames += 'row-disabled';
  }
  
  return classNames;
}

// 搜索按钮操作
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

// 重置按钮操作
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 行点击事件
function handleRowClick(row, column, event) {
  // 只有可选择的仓库才能被选中
  if (isWarehouseSelectable(row)) {
    selectedWarehouse.value = row;
    selectedRowIndex.value = warehouseList.value.findIndex(item => item.warehouseId === row.warehouseId);
  } else {
    // 提示用户该仓库不可选择
    proxy.$modal.msgWarning(`该仓库当前状态不可用，请选择正常状态的仓库`);
  }
}

// 选择仓库
function selectWarehouse(row) {
  if (isWarehouseSelectable(row)) {
    selectedWarehouse.value = row;
    selectedRowIndex.value = warehouseList.value.findIndex(item => item.warehouseId === row.warehouseId);
  }
}

// 确认选择，返回仓库信息
function confirmSelection() {
  if (selectedWarehouse.value) {
    emit('select', selectedWarehouse.value);
    handleClose();
  }
}

// 关闭对话框
function handleClose() {
  emit('update:visible', false);
  selectedWarehouse.value = null;
  selectedRowIndex.value = null;
}

// 打开方法，由父组件调用
function open() {
  visible.value = true;
  reset();
  getList();
}

// 重置方法
function reset() {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    warehouseCode: null,
    warehouseName: null,
    warehouseType: null,
    status: null
  };
  selectedWarehouse.value = null;
  selectedRowIndex.value = null;
}

// 对外暴露方法
defineExpose({
  open
});
</script>

<style scoped>
.warehouse-selector .row-selected {
  background-color: #f0f9eb !important;
}

.warehouse-selector .row-disabled {
  background-color: #f9f9f9 !important;
  color: #999 !important;
  cursor: not-allowed !important;
}
</style> 